#include "Log.h"
#include <iostream>
#include <fstream>
#include <stdarg.h>
#include <string>
#include <list>
#include <time.h>

using namespace std;


class CLog::IMPL
{
public:
	IMPL();
	~IMPL();

	void Log(const char * fmt, va_list args);

private:
	list<string> m_cache;
	ofstream m_logFile;
	
	void Flush();
};

CLog::IMPL::IMPL()
{
	m_logFile.open("Log.txt",ios_base::out | ios_base::trunc);
}

CLog::IMPL::~IMPL()
{
	Flush();
	m_logFile.close();
}

void CLog::IMPL::Log(const char * fmt, va_list args)
{
	char msg[1024];
	char buffer[1024];
	char timebuffer[30];

	// Get Time
	struct tm newtime;
	__time64_t long_time;

	_time64( &long_time ); 
	_localtime64_s( &newtime, &long_time );
	asctime_s( timebuffer, sizeof(timebuffer), &newtime );
	
	// format the message part
	vsprintf_s(msg,sizeof(msg),fmt,args);

	// format the whole log
	sprintf_s(buffer,sizeof(buffer),"%.19s : %s",timebuffer,msg);

	string str(buffer);

	m_cache.push_back(str);

	if (m_cache.size() >= 50)
	{
		Flush();
	}
}

void CLog::IMPL::Flush()
{
	for (list<string>::iterator it = m_cache.begin(); it != m_cache.end(); ++it)
	{
		m_logFile << *it << endl;
	}

	m_cache.clear();
}

CLog::CLog()
{
	pImplement = new CLog::IMPL();
}

CLog::~CLog()
{
	delete pImplement;
}

void CLog::Log(const char* fmt, ...)
{
	va_list args;
	va_start(args, fmt);

	pImplement->Log(fmt,args);
}